<?php

namespace App\Models;

use Illuminate\Support\Collection;

class Pintuan extends Model
{
    protected $table = 'yf_pintuan';
    public $timestamps = false;
    protected $guarded = ['id'];

    /**
     * 首页版块中补齐拼团商品信息
     *
     * @param array $ids
     * @param int $size
     * @return Collection
     */
    public static function getOpenPintuan(array $ids, int $size) : Collection
    {
        $now = now()->toDateTimeString();
        $pintuans = self::from('yf_pintuan as a')
            ->select(
                'a.id as pintuan_id', 'a.name as pintuan_name', 'a.person_num', 'b.goods_id', 'b.price',
                'b.price_one', 'b.price_ori', 'b.id as detail_id', 'c.goods_name', 'c.goods_image as goods_image'
            )
            ->leftJoin('yf_pintuan_detail as b', 'b.pintuan_id', '=', 'a.id')
            ->leftJoin('yf_goods_base as c', 'c.goods_id', '=', 'b.goods_id')
            ->where([
                ['a.start_time', '<', $now],
                ['a.end_time', '>', $now],
                ['a.status', '=', 1]
            ])
            ->when($ids, function ($query) use ($ids) {
                return $query->whereNotIn('a.id', $ids);
            })
            ->orderBy('a.id')
            ->limit($size)
            ->get();

        $pintuans->each(function ($pintuan) {
            $pintuan->buyer_count = PintuanBuyer::whereDetailId($pintuan->detail_id)->count();
        });

        return $pintuans;
    }

    public static function getPintuanGoodsByIds(array $ids) : Collection
    {
        $now = now()->toDateTimeString();
        return self::where('start_time', '<', $now)
            ->where('end_time', '>', $now)
            ->where('status', 1)
            ->whereIn('id', $ids)
            ->get();
    }
}
